package com.lenovo.study.controller;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Author: fuxh3@lenovo.com
 * Date: Created in 2017/8/23 0023
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {
    private static final Logger logger = LogManager.getLogger(FileController.class);
    @RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("lenovoFile") MultipartFile file){
        if(file.isEmpty()){
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为: "+fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的文件名的后缀名"+suffixName);
        fileName = UUID.randomUUID().toString()+suffixName;
        String filePath = "D:/lenovo/upload/";
        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";

    }
}
